package com.gary.springcloud.controller;

import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.gary.springcloud.service.PaymentService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.Assert;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;

/**
 * @author peng_rui
 * @date 2022/7/31
 */
@Slf4j
@RestController
public class CircleBreakerController {
    public static final String SERVICE_URL = "http://nacos-provider";

    @Resource
    private RestTemplate restTemplate;

    @Resource
    private PaymentService paymentService;

    /**
     * restTemplate  ribbon 调用
     * @param id
     * @return
     */
//    @SentinelResource(value = "fallback", fallback = "handlerFallBack")  //fallback
//    @SentinelResource(value = "blockHandler", blockHandler = "blockHandler") //block
    @SentinelResource(value = "payment", blockHandler = "blockHandler", fallback = "handlerFallBack") //block + fallback
    @RequestMapping(value = "/consumer-84/payment/{id}", method = RequestMethod.GET)
    public String payment(@PathVariable("id") Long id) {
        String result = restTemplate.getForObject(SERVICE_URL + "/paymentSql/" + id, String.class);
        Assert.isTrue(id != 4, "id == 4");
        return result;
    }

    /**
     * paymentFeign 调用
     * @param id
     * @return
     */
//    @SentinelResource(value = "paymentFeign", blockHandler = "blockHandler", fallback = "handlerFallBack") //block + fallback
    @RequestMapping(value = "/consumer-feign-84/payment/{id}", method = RequestMethod.GET)
    public String paymentFeign(@PathVariable("id") Long id) {
        String result = paymentService.paymentSql(id);
        Assert.isTrue(id != 4, "id == 4");
        return result;
    }

    /**
     * 注意 必须要加  BlockException e 参数 否则降级无法生效
     * @param id
     * @param e
     * @return
     */
    public String blockHandler(@PathVariable("id") Long id, BlockException e) {
        return "系统繁忙 blockHandler 降级";
    }

    public String handlerFallBack(@PathVariable("id") Long id) {
        return "系统繁忙 handlerFallBack 降级";
    }

}
